package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppJwtUtil;
import com.heima.media.dto.LoginDto;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmUserMapper;
import com.heima.media.service.IWmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 自媒体用户信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-01-11
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements IWmUserService {

    @Override
    public ResponseResult<WmUser> saveWmUser(WmUser entity) {
        // 判断用户是否已经存在,通过 ap_user_id 来判断
        LambdaQueryWrapper<WmUser> query = new LambdaQueryWrapper<>();
        query.eq(WmUser::getApUserId, entity.getApUserId());
        WmUser one = this.getOne(query);
        if (one != null) {
            return ResponseResult.okResult(one);
        }
        // 保存自媒体用户
        entity.setCreatedTime(new Date());
        this.save(entity);
        return ResponseResult.okResult(entity);
    }

    @Override
    public ResponseResult login(LoginDto dto) {
        // 需求分析
        // 判断用户名和密码是否为空
        if (dto == null || StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 根据用户名查询用户
        LambdaQueryWrapper<WmUser> query = new LambdaQueryWrapper<>();
        query.eq(WmUser::getName, dto.getName());
        WmUser one = this.getOne(query);
        // 判断用户是否存在
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 用户存在,获取用户的盐salt
        // 使用用户传入的密码+salt进行md5加密
        String pwd = dto.getPassword() + one.getSalt();
        String pass = DigestUtils.md5DigestAsHex(pwd.getBytes());
        // 加密后的字符串和数据库中的密码进行对比
        if (!pass.equals(one.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 密码一致,需要通过JWT生成token
        Map<String, Object> claimMap = new HashMap<>();
        claimMap.put("userId", one.getId());
        claimMap.put("userName", one.getName());
        String token = AppJwtUtil.getToken(claimMap);
        // 给前端返回用户信息和token
        Map<String, Object> map = new HashMap<>();
        // 隐藏用户敏感信息
        one.setPassword(null);
        one.setSalt(null);
        one.setPhone(null);
        map.put("user", one);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
